package com.boot.controller;

import java.util.concurrent.CompletableFuture;
import java.util.function.Function;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.boot.param.Student;
import com.boot.param.TempCacheModel;
import com.boot.service.CacheMap;

/**
 * @author onlyone
 */
@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private CacheMap cacheMap;

    /**
     * http://localhost:8096/test/first_do
     */
    @RequestMapping(value = "/first_do")
    public String firstDo() {
        Student student = new Student();
        student.setName("TomGe");
        student.setScore(80);

        // 外部扩展接口
        Function<Integer, Student> function = t -> {
            // 此处可以处理一些业务逻辑，比如拿到短信验证码，开始登录

            if (t == 10) {
                int i = 1 / 0; // 人为制造异常
            }
            student.addScore(t);
            return student;
        };

        // 对现存对象的处理逻辑放入CompletableFuture
        CompletableFuture<Integer> f1 = new CompletableFuture();
        f1.thenApply(t -> { // t相当于短信验证码
            return function.apply(t);
        }).whenComplete((s, e) -> {

            if (e != null) {
                // 异常处理
                System.out.println("异常信息：" + e);
            } else {
                // 正常处理
                System.out.println("当前子任务结束：" + JSON.toJSONString(s));
            }

            // 。。。。。。。此处可以继续后续流程
        });

        // 将CompletableFuture放在本地缓存中
        TempCacheModel tempCacheModel = new TempCacheModel();
        tempCacheModel.setCompletableFuture(f1);
        cacheMap.getCache().put("1", tempCacheModel);

        System.out.println("first_do，运行结果:" + JSON.toJSONString(student));

        return "sucess";
    }

    /**
     * <pre>
     * http://localhost:8096/test/continue_do?t=11 
     * 
     * http://localhost:8096/test/continue_do?t=10
     * </pre>
     */
    @RequestMapping(value = "/continue_do")
    public String continue_do(@RequestParam("t") Integer t) {
        TempCacheModel tempCacheModel = (TempCacheModel) cacheMap.getCache().get("1");
        tempCacheModel.getCompletableFuture().complete(t);

        return "sucess";
    }

}
